import { AxiosResponse } from "axios";
import { objectToUrlParams } from "/@/utils/common";
import service from "/@/utils/request";
import { ExportParam, SystemParam } from "/@/_types/api";
import { ReturnPage } from "/@/_types/api/return-type";
import { SYSTEM_CONFIG } from '/@/config/system'
export interface IQueryServiceApi {
    /**
     * 导出数据
     * @param exportParam 导出参数
     * @param params 其他参数
     */
    exportData(exportParam?: ExportParam | null, params?: any): Promise<AxiosResponse<Blob>>
    /**
     * 分页查询方法 
     * @param systemParam 系统参数
     * @param queryParam 查询参数
     */
    queryPage(systemParam?: SystemParam | null, queryParam?: any): Promise<AxiosResponse<ReturnPage>>,
    /**查询 直接查询bean.xml里面的sql 由于这个方法可以返回分页 查询所有数据 所以无法确定返回类型*/
    query(queryParam?: any): Promise<AxiosResponse<any>>,
    /**
     * 分页查询方法 
     * @param systemParam 系统参数
     * @param queryParam 查询参数
     */
    queryList(systemParam?: SystemParam | null, queryParam?: any): Promise<AxiosResponse<any[]>>,
}

export class QueryServiceApi implements IQueryServiceApi {
    //primaryKey: string;
    protected baseUrl: string;//例 /org/user => list url => /org/user/list
    /**
     * 需要传入baseUrl
     * @param baseUrl baseurl 例：/org/user
     */
    constructor(baseUrl: string) {
        if (!baseUrl) throw new Error("baseUrl not null.");
        this.baseUrl = baseUrl;
    }
    exportData(exportParam?: ExportParam | null, params?: any): Promise<AxiosResponse<Blob>> {
        //默认导出 querylist
        let queryName = "QueryList";
        if (exportParam && exportParam.queryName) {
            queryName = exportParam.queryName[0].toLocaleUpperCase() + exportParam.queryName.substring(1, exportParam.queryName.length)
            delete exportParam.queryName;
        }
        let url = this.baseUrl + "/export" + queryName;
        url += objectToUrlParams({ ...params, ...exportParam }, true)
        return service.post(url, null, { responseType: 'blob', timeout: SYSTEM_CONFIG.downloadFileTimeout })
    }
    queryPage(systemParam?: SystemParam | null, queryParam?: any): Promise<AxiosResponse<ReturnPage>> {
        let queryName = "QueryList";
        if (systemParam && systemParam.queryName) {
            queryName = systemParam.queryName[0].toLocaleUpperCase() + systemParam.queryName.substring(1, systemParam.queryName.length)
            delete systemParam.queryName;
        }
        let url = this.baseUrl + "/page" + queryName;
        return service.get(url, { params: { ...systemParam, ...queryParam } });
    }
    query(queryParam?: any): Promise<AxiosResponse<any>> {
        let url = this.baseUrl + "/query";
        return service.get(url, { params: queryParam })
    }
    queryList(systemParam?: SystemParam | null, queryParam?: any): Promise<AxiosResponse<any[]>> {
        let url = this.baseUrl + "/queryList";
        return service.get(url, { params: { ...systemParam, ...queryParam } });
    }
}